package utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public abstract class Utils {

	/**
	 * Obtiene la suma md5 de una cadena
	 * 
	 * @param input
	 *            Cadena a codificar
	 * @return Cadena md5 que representa a la entrada (o null en caso de error)
	 * @throws NoSuchAlgorithmException
	 */
	public static String md5sum(String input) {

		if (input == null) {
			throw new IllegalArgumentException("Input cannot be null!");
		}

		StringBuffer sbuf = new StringBuffer();
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			byte[] raw = md.digest(input.getBytes());

			for (int i = 0; i < raw.length; i++) {
				int c = (int) raw[i];
				if (c < 0) {
					c = (Math.abs(c) - 1) ^ 255;
				}
				String block = toHex(c >>> 4) + toHex(c & 15);
				sbuf.append(block);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}

		return sbuf.toString();

	}

	private static final String toHex(int s) {
		if (s < 10) {
			return new StringBuffer().append((char) ('0' + s)).toString();
		} else {
			return new StringBuffer().append((char) ('A' + (s - 10)))
					.toString();
		}
	}
	
	public static void main(String[] args){
		System.out.println("admin: " + md5sum("admin"));
	}

}
